package com.huo.importdata.service;

import com.huo.common.dao.TableIndexMapper;
import com.huo.common.enumtype.FtpFileStatusEnum;
import com.huo.filestransport.dao.FtpFileInfoDao;
import com.huo.filestransport.entity.FtpFileInfoEntity;
import com.huo.filestransport.vo.FtpServerInfo;
import com.huo.importdata.dao.CifmMapper;
import com.huo.importdata.entity.Cifm;
import com.huo.util.DateUtils;
import com.huo.util.FileSplit;
import org.quartz.DisallowConcurrentExecution;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.*;
import java.util.concurrent.CountDownLatch;

@Service
@DisallowConcurrentExecution
public class ImportDataCifmService {

    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private FtpFileInfoDao ftpFileInfoDao;
    @Autowired
    private CifmMapper cifmMapper;
    @Autowired
    private FileSplit fileSplit;
    @Autowired
    private TableIndexMapper tableIndexMapper;

    @Autowired
    private FtpServerInfo ftpServerInfo;


    private final static int insertBatchNum = 300;

    private final static int splipFileNum = 3;
    //@TaskLogAnnotation
    public void importCifm(){
        String dataDate = DateUtils.DateCount(ftpServerInfo.getDelayTime(),"yyyy-MM-dd");
        importCifm(dataDate);
    }
    //@TaskLogAnnotation
    public void importCifm(String dataDate){
        logger.info("导入cifm21数据开始" );
        try {
            FtpFileInfoEntity record = new FtpFileInfoEntity();
            record.setFtpfilestatus(FtpFileStatusEnum.FTPFIEL_STATUS_UNZIP.getCode());
            record.setFtpfilename("S01_CIFM21.zip");
            record.setDataDateStr(dataDate);
            FtpFileInfoEntity ffe = ftpFileInfoDao.selectBySelective(record);
            if(ffe != null){
                //将表中数据删除
                cifmMapper.truncateTableCifm();
                Map<String,Object> map = new HashMap<>();
                map.put("tablename","t_temp_cifm");
                map.put("indexname","T_TEMP_CIFM_CCUSNO");
                tableIndexMapper.dropIndex(map);
                String unzipfilePaht = ffe.getUnzipfilepath();
                logger.info("拆分{}文件开始",unzipfilePaht );
                fileSplit.splitFile(unzipfilePaht,splipFileNum);
                logger.info("拆分{}文件结束,拆分文件数{}",unzipfilePaht,splipFileNum );
                logger.info("多线程插入数据开始,线程数：{}", splipFileNum);
                long startT = System.currentTimeMillis();
                final CountDownLatch latch = new CountDownLatch(splipFileNum);
                for(int i = 1 ; i <= splipFileNum ; i++){
                    int finalI = i;
                    Thread t = new Thread(new Runnable() {
                        @Override
                        public void run() {
                            logger.info("线程 {}开始",finalI);
                            BufferedInputStream fis = null;
                            BufferedReader reader = null;
                            try {
                                long start = System.currentTimeMillis();
                                File file = new File(unzipfilePaht + finalI);
                                fis = new BufferedInputStream(new FileInputStream(file));
                                reader = new BufferedReader(new InputStreamReader(fis,"utf-8"),20*1024*1024);
                                String line = "";
                                int dataNum = 0;
                                //插入次数
                                int insertNum = 0;
                                List<Cifm> list = new ArrayList<>();
                                while((line = reader.readLine()) != null){
                                    String[] str = line.split("\u001B");
                                    //System.out.println(Arrays.toString(str));
                                    Cifm cifm = new Cifm();
                                    cifm.setCcusno(str[0]);
                                    cifm.setCaccno(str[1]);
                                    cifm.setCacctyp(str[2]);
                                    cifm.setCorgno(str[3]);
                                    cifm.setCflag(str[4]);
                                    list.add(cifm);
                                    if(list.size() == insertBatchNum){
                                        cifmMapper.insertBatch(list);
                                        list.clear();
                                        insertNum ++ ;
                                    }
                                    dataNum ++;
                                }
                                if(dataNum != insertNum * insertBatchNum){
                                    cifmMapper.insertBatch(list);
                                }
                                long end = System.currentTimeMillis();
                                logger.info("线程 {}保存数据{},运行时间{}",finalI,dataNum,end-start);
                                latch.countDown();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }finally {
                                try {
                                    reader.close();
                                    fis.close();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    });
                    t.start();
                }
                latch.await();
                long endT = System.currentTimeMillis();
                logger.info("多线程插入数据结束,导入数据时间：{}",endT-startT);
                FtpFileInfoEntity param = new FtpFileInfoEntity();
                param.setId(ffe.getId());
                param.setFtpfilestatus(FtpFileStatusEnum.FTPFIEL_STATUS_IMPORT.getCode());
                param.setUpdatetime(new Date());
                ftpFileInfoDao.updateByPrimaryKeySelective(param);
                map.put("tablecloum","CCUSNO");
                tableIndexMapper.createIndex(map);
            }else {
                logger.info("未查询到S01_CIFM21.zip文件" );
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        logger.info("导入cifm21数据结束" );
    }

}
